package com.ala4.oxcafe.oauth;

import com.ala4.oxcafe.boot.enums.UserTypeEnum;
import com.ala4.oxcafe.boot.manager.CustomUserDetails;
import com.ala4.oxcafe.boot.userdetails.WeChatUserDetailsService;
import com.ala4.oxcafe.common.utils.collection.CollUtil;
import com.ala4.oxcafe.entity.WeChatUser;
import com.ala4.oxcafe.repository.WeChatUserRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户微信登录
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/12 09:33
 */
@Slf4j
@Service
@AllArgsConstructor
public class WeChatUserDetailsServiceImpl implements WeChatUserDetailsService {

    private final WeChatUserRepository weChatUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("WeChatUserDetailsServiceImpl-loadUserByUsername {}", username);

        // 微信手机号登录
//        WeChatUser weChatUser = weChatUserRepository.wxPhoneLogin(username);

        // 微信openid登录
        WeChatUser weChatUser = weChatUserRepository.wxOpenIdLogin(username);

        CustomUserDetails customUserDetails = new CustomUserDetails();
        customUserDetails.setUserId(weChatUser.getId());
        customUserDetails.setUserAccount(weChatUser.getPhoneNumber());
        customUserDetails.setUserType(UserTypeEnum.WE_CHAR);
        customUserDetails.setPhone(weChatUser.getPhoneNumber());
        customUserDetails.setNickName(weChatUser.getNickName());
        customUserDetails.setAvatar(weChatUser.getAvatar());
        customUserDetails.setRoles(CollUtil.newArrayList("R_WX_USER"));
        customUserDetails.setStatus(0);
        customUserDetails.setIsStoreUser(1);

        return customUserDetails;
    }
}
